package com.zzyl.nursing.service.impl;

import java.util.Collections;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;
    private static final List<String> NICK_NAME_PREFIX_LIST = Arrays.asList("钱途无量",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    /**
     * 小程序登录
     *
     * @param dto 前端传过来的参数
     * @return 返回的数据
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1.获取openId
        String openid = wechatService.getOpenid(dto.getCode());
        //2.根据openId查询用户信息
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openid).one();
        //3.判断查询到的信息是否为空,为空的话新增\
        //打乱集合
        Collections.shuffle(NICK_NAME_PREFIX_LIST);

        if (member == null) {
           member = FamilyMember.builder()
                   .openId(openid)
                   //集合中的随机元素加上四个随机数
                   .name(NICK_NAME_PREFIX_LIST.get(0)+ RandomStringUtils.randomNumeric(4))
                   .build();
              this.save(member);
        }
        //4.判断用户的手机号是否存在
        if (StrUtil.isBlank(member.getPhone())){
            //手机号为空
            String phoneNumber = wechatService.getPhoneNumber(dto.getPhoneCode());
            if (StrUtil.isNotBlank(phoneNumber)) {
                //获取手机号后更新数据
                FamilyMember familyMember = FamilyMember.builder()
                        .id(member.getId())
                        .phone(phoneNumber)
                        .build();
                this.updateById(familyMember);
            }
        }
        //5.生成令牌
        String token = tokenService.createToken(Map.of("userId", member.getId(),
                "username", member.getName()
        ));
        //6.封装返回数据
        return new LoginVo(token,member.getName());
    }
}

